package com.hj.security.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

/**
 * @author hj
 * @Date 2023/4/26
 * @Description: 接口权限判断工具.用着就是玩, 直接 hasAuthority 也一样..
 */
@Slf4j
@Component("pms")
public class PermissionUtil {

    /**
     * 判断对接口是否有权限
     *
     * @param permission 权限
     * @return 布尔
     */
    public boolean hasPermission(String permission) {
        if (StrUtil.isBlank(permission)) {
            return true;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication) {
            return false;
        }
        return authentication
                .getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .filter(StringUtils::hasText)
                .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
    }


}